package com.wzy.pictureviewfliper;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import java.util.ArrayList;

/**
 * Created by wangzhenyu on 2016/7/28.
 */
public class ImageTextFlipper extends RelativeLayout {

    private Context mContext;
    private ViewFlipper mImageFlipper, mTextFlipper;
    private Handler mHandler;

    public ImageTextFlipper(Context context) {
        this(context, null);
    }

    public ImageTextFlipper(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ImageTextFlipper(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mHandler = new Handler();
        LayoutInflater.from(context).inflate(R.layout.imagetextflipper, this);
        mImageFlipper = (ViewFlipper) findViewById(R.id.image_flipper);
        mTextFlipper = (ViewFlipper) findViewById(R.id.text_flipper);
        mImageFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.scroll_in));
        mImageFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.scroll_out));
        mTextFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.scroll_in));
        mTextFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.scroll_out));
    }

    public void setData(ArrayList<Item> datas) {
        for (int i = 0; i < datas.size(); i++) {
            Item item = datas.get(i);
            ImageView imageview = new ImageView(mContext);
            imageview.setImageResource(item.getImageId());
            imageview.setScaleType(ImageView.ScaleType.FIT_XY);
            mImageFlipper.addView(imageview);
            TextView textView = new TextView(mContext);
            textView.setText(item.getText());
            mTextFlipper.addView(textView);
        }
    }

    public void showNext(long delayMillis) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                mImageFlipper.showNext();
                mTextFlipper.showNext();
            }
        };
        mHandler.removeCallbacks(runnable);
        mHandler.postDelayed(runnable, delayMillis);

    }
}
